# -*- coding: utf-8 -*-
"""
@File:    file_process.py
@Author:  jk.dong
@Desc:    文件处理
"""
import logging
import re
import base64
import hashlib
import xml.dom.minidom
from pathlib import Path


def check_suffix_compatible(filename: str, compatible_list: list):
    """
    检查文件名后缀是否符合
    pdf,doc,xls,ppt,docx,xlsx,pptx等
    """
    file_suffix = filename.split('.')[-1]
    if file_suffix in compatible_list:
        return True
    else:
        return False


def check_directory_exist(path, not_empty=False, create=True):
    """
    检查路径是否存在，若不存在就创建
    :param path:
    :param not_empty: if true 直接退出
    :param create:
    :return:
    """
    if not path:
        if not_empty:
            raise RuntimeError('func: check_directory_exist param path error: path为空')
    if path.exists() and not path.is_dir():
        logging.warning(f'{path}不是一个目录')
    if not path.exists() and create:
        path.mkdir(parents=True, exist_ok=True)
        if path.exists():
            logging.info(f'路径{path} 创建成功')
        else:
            raise RuntimeError(f'创建路径失败:{path}，请检查文件权限')


def get_md5(filename):
    with open(filename, 'rb') as f:
        m = hashlib.md5()
        while True:
            # 如果不用二进制打开文件，则需要先编码
            # data = f.read(1024).encode('utf-8')
            data = f.read(1024)  # 将文件分块读取
            if not data:
                break
            m.update(data)

        byte_digest = m.digest()

    digest = (base64.b64encode(byte_digest)).decode('utf-8')
    return digest


def compare_digest_files(md5_value: str, attach_files: list) -> bool:
    """
    获取附件的MD5值来校验入参md5_value是否匹配
    :param md5_value: 待匹配的MD5值
    :param attach_files: 附件列表对象
    :return: boolean
    """
    for f in attach_files:
        file_path = f.get('path')
        if file_path:
            file_md5 = get_md5(file_path)
            if file_md5 != md5_value:
                continue
            else:
                return True
    return False


def match_files_by_pattern(directory, pattern_str):
    """
    根据正则表达式匹配路径下文件
    """
    directory = Path(directory)
    pattern = re.compile(pattern_str)
    for file_path in directory.iterdir():
        if file_path.is_file():
            if pattern.match(file_path.name):
                # matched_files.append(file_path)
                return file_path
    return None


def save_file(data, filename, directory):
    """
    模拟with open写入文件，打印相关信息
    """
    try:
        filepath = directory.joinpath(filename)
        logging.info(f"Save to {filepath}")
        f = open(filepath, 'wb') if isinstance(data, bytes) else open(filepath, 'w')
    except Exception as err:
        logging.error(f"{directory.joinpath(filename)} open failed. Error:{err}")
    else:
        f.write(data)
        f.close()


def save_body_source(msg, rawmaillog_id, save_path):
    """保存html文件，附件名统一成xn_bodySource.html"""
    file_name = f"{rawmaillog_id}.html"
    if msg.body_html:
        save_file(msg.body_html, file_name, save_path)
    elif msg.body_text:
        save_file(msg.body_text, file_name, save_path)
    logging.info("邮件消息内容存为html文件成功！")
    msg.add_attachment("xn_bodySource.html", Path(save_path).joinpath(file_name))


def get_xml(name, data, write_time):
    # 在内存中创建一个空的文档
    data['uid'] = data["UID"]
    data['buysidedocid'] = data['DOCID']
    data['sellsidedocid'] = data['SELLSIDEDOCID']
    data['mailfrom'] = data['MAILFROM']
    data['writetime'] = write_time.strftime("%Y-%m-%d %H:%M:%S")
    doc = xml.dom.minidom.Document()
    root = doc.createElement('info')
    doc.appendChild(root)

    node_list = ['uid', 'buysidedocid', 'sellsidedocid', 'mailfrom', 'writetime']
    data_keys = data.keys()
    for i in node_list:
        if i in data_keys:
            node_name = doc.createElement(i)
            node_name.appendChild(doc.createTextNode(str(data.get(i))))
            root.appendChild(node_name)

    # 开始写xml文档
    fp = open(name, 'w')
    doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="GB2312")


def read_xml(name):
    result = {}
    try:
        with open(name, "r", encoding="GB2312") as f:
            xml_file_string = f.read()
            # 编码转换
            xml_file_string = xml_file_string.replace('<?xml version="1.0" encoding="GB2312"?>',
                                                      '<?xml version="1.0" encoding="utf-8"?>')
            xml_file_string = xml_file_string.encode('utf-8')
            doc = xml.dom.minidom.parseString(xml_file_string)
            # 获取根元素
            root = doc.documentElement

            uid_node = root.getElementsByTagName('uid')[0]
            if uid_node:
                result["uid"] = uid_node.childNodes[0].data
            buysidedocid_node = root.getElementsByTagName('buysidedocid')[0]
            if buysidedocid_node:
                result["buysidedocid"] = buysidedocid_node.childNodes[0].data
            sellsidedocid_node = root.getElementsByTagName('sellsidedocid')[0]
            if sellsidedocid_node:
                result["sellsidedocid"] = sellsidedocid_node.childNodes[0].data
            mailfrom_node = root.getElementsByTagName('mailfrom')[0]
            if mailfrom_node:
                result["mailfrom"] = mailfrom_node.childNodes[0].data
            # writetime_node = root.getElementsByTagName('writetime')[0]
            # result["writetime"] = writetime_node.childNodes[0].data
    except Exception as err:
        logging.error(f"Parse xml file error: {err}")

    return result

